import Loading from '@/components/loading';
import systemService from '@/services/system';
import { BfPage, BfResult } from '@bud-fe/react-pc-ui';
import { authHelper } from '@bud-fe/utils';
import { isInIcestark } from '@ice/stark-app';
import { store as starkStore } from '@ice/stark-data';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import { IAppConfig, runApp } from 'ice';
import './arms';
import request from './utils/request';
import { fetchAuthData } from './utils/tools';

const appConfig: IAppConfig = {
  app: {
    rootId: 'ice-container',
    addProvider: ({ children }) => <ConfigProvider locale={zhCN}>{children}</ConfigProvider>,
    getInitialData: async () => {
      // 初始化 BfPage 中登录页、忘记密码页需要的参数
      BfPage.configRequest({
        request,
        // TODO: 请替换成对应的 systemId。1代表业务中台
        systemId: 24,
      });
      // 是否为子应用运行
      if (isInIcestark()) {
        const data = starkStore.get('data');
        console.log('starkStore data', data);
        if (data) {
          const { tokenName, token, auth } = data;
          authHelper.setToken(tokenName, token);
          return { auth };
        }
        return { auth: { isLogin: false } };
      } else {
        if (!authHelper.getToken()) {
          return { auth: { isLogin: false } };
        }
        const [userInfo, authData] = await Promise.all([systemService.getUserInfo(), fetchAuthData()]);
        const { auth, menuData } = authData;
        return { auth, initialStates: { user: { menuData, ...userInfo } } };
      }
    },
  },
  auth: {
    // 无权限时的展示组件
    NoAuthFallback: <BfResult status="403" />,
  },
  router: {
    type: 'browser',
    // 开启按需加载时配置 fallback UI
    fallback: <Loading />,
  },
};

runApp(appConfig);
